<template>
  <page-header-wrapper>
    <a-card>
      <JeepaySearchForm :searchFunc="searchFunc" :resetFunc="onReset">
        <a-form-item label="" class="table-search-item">
          <JeepayDateRangePicker ref="dateRangePicker" v-model:value="vdata.searchData['queryDateRange']" customDateRangeType="date" />
        </a-form-item>
        <JeepaySearchInfoInput v-model:value="vdata.searchData['mchNo']" placeholder="商户号" :textUpStyle="true" :mchNoAndName="true" showType="MCH" />

        <jeepay-text-up v-model:value="vdata.searchData.mbrId" :placeholder="'会员ID'" />
        <jeepay-text-up v-model:value="vdata.searchData.mbrName" :placeholder="'会员名称'" />
        <jeepay-text-up v-model:value="vdata.searchData.mbrTel" :placeholder="'会员手机号'" />
        <a-form-item label="" class="table-search-item">
          <a-select v-model:value="vdata.searchData.state" placeholder="状态">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="0">禁用</a-select-option>
            <a-select-option value="1">启用</a-select-option>
          </a-select>
        </a-form-item>
      </JeepaySearchForm>

      <!-- 列表渲染 -->
      <JeepayTable
        ref="infoTable"
        :initData="true"
        :reqTableDataFunc="reqTableDataFunc"
        :tableColumns="tableColumns"
        :searchData="vdata.searchData"
        rowKey="mbrId"
        :statisticsIsShow="$access('ENT_MEMBER_LIST')"
        :tableExportFunc="tableExportFunc"
        @btnLoadClose="vdata.btnLoading=false"
      >
        <template #statistics>
          <div class="statistics-list">
            <div v-for="(item, index) in countList" :key="index" class="item">
              <div v-if="item.type == 'line'" class="line" />
              <div class="title">{{ item.title }}</div>
              <div v-if="item.title" class="amount" :style="{color: item.textColor}">
                <span class="amount-num">{{ item.content }}</span>
                <span v-if="item.isMoney">元</span>
              </div>
            </div>
          </div>
        </template>
        <template #topBtnSlot>
          <div>
            <a-button v-if="$access('ENT_MEMBER_ADD')" type="primary" class="mg-b-30" @click="addFunc"><plus-outlined />新建</a-button>
          </div>
        </template>
        <template #bodyCell="{column,record}">
          <template v-if="column.key == 'balance'">
            <b>￥{{ record.balance / 100 }}</b>
          </template> <!-- 自定义插槽 -->
          <template v-if="column.key == 'state'">
            <a-badge :status="record.state === 0?'error':'processing'" :text="record.state === 0?'禁用':'启用'" />
          </template>

          <template v-if="column.key == 'op'">
            <!-- 操作列插槽 -->
            <JeepayTableColumns>
              <a-button v-if="$access('ENT_MEMBER_EDIT')" type="link" @click="editFunc(record.mbrId)">修改</a-button>
              <a-button v-if="$access('ENT_MEMBER_MANUAL')" type="link" @click="accountChangeFunc(record.mbrId)">调账</a-button>
              <a-button v-if="$access('ENT_MEMBER_ACCOUNT_HISTORY_LIST')" type="link" @click="accountFunc(record.mbrId)">账户流水</a-button>
              <a-button v-if="$access('ENT_MEMBER_RECHARGE_RECORD_LIST')" type="link" @click="rechargeFunc(record.mbrId)">充值流水</a-button>
              <!-- <a-button v-if="$access('ENT_MEMBER_DELETE')" type="link" style="color: red" @click="delFunc(record.mbrId)">删除</a-button> -->
            </JeepayTableColumns>
          </template>
        </template>
      </JeepayTable>
    </a-card>
    <!-- 新增  -->
    <MemberAddOrEdit ref="memberAddOrEdit" :callbackFunc="searchFunc" />
    <!-- 调账  -->
    <ChangeBalance ref="changeBalance" :callbackFunc="searchFunc" />
  </page-header-wrapper>
</template>

<script lang="ts" setup>
import { API_URL_MEMBER_LIST, req, $exportExcel, exportExcelUrl, $memberInfoCount } from '@/api/manage'
import MemberAddOrEdit from './AddOrEdit.vue'
import ChangeBalance from './ChangeBalance.vue'
import {ref, reactive, getCurrentInstance } from 'vue'
import router from '@/router'
import fileDownload from 'js-file-download'
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

// eslint-disable-next-line no-unused-vars
const tableColumns = reactive([
  { key: 'mbrId', fixed: 'left', title: '会员ID', dataIndex: 'mbrId' },
  { key: 'mchNo', title: '商户号', dataIndex: 'mchNo' },
  { key: 'mbrName', title: '会员名称', dataIndex: 'mbrName' },
  { key: 'mbrTel', title: '手机号', dataIndex: 'mbrTel' },
  { key: 'balance', title: '账户余额', dataIndex: 'balance' },
  { key: 'state', title: '状态',},
  { key: 'createdAt', title: '创建日期', dataIndex: 'createdAt',},
  { key: 'op', title: '操作', fixed: 'right', align: 'center' }
])

  const memberAddOrEdit = ref()
  const changeBalance = ref()
  const infoTable = ref()
  const dateRangePicker = ref()
  let countList:any = ref([]) // 数据统计数组

  const vdata = reactive({
    btnLoading: false,
    tableColumns: tableColumns,
    searchData: {} as any
  })

  // 请求table接口数据
  function reqTableDataFunc(params){
    getCount()
    return req.list(API_URL_MEMBER_LIST, params)
  }

  function searchFunc () { // 点击【查询】按钮点击事件
    getCount()
    infoTable.value.refTable(true)
  }

  function addFunc() { // 业务通用【新增】 函数
    memberAddOrEdit.value.show(vdata.searchData['mchNo'])
  }

  function editFunc (recordId) { // 业务通用【修改】 函数
    memberAddOrEdit.value.show(vdata.searchData['mchNo'], recordId)
  }

  function accountChangeFunc (recordId) { // 调账 函数
    changeBalance.value.show(recordId)
  }

  function accountFunc (recordId: any) { // 账户流水
      router.push({
        path: '/member/account',
        query: { mbrId: recordId }
      })
  }

  function rechargeFunc (recordId: any) { // 充值记录
      router.push({
        path: '/member/recharge',
        query: { mbrId: recordId }
      })
  }

  function delFunc (appId) { 
    $infoBox.confirmDanger('确认删除？', '', () => {
      req.delById(API_URL_MEMBER_LIST, appId).then(res => {
        $infoBox.message.success('删除成功！')
        searchFunc()
      })
    })
  }

  function tableExportFunc(){
    return $exportExcel(exportExcelUrl.memberInfo, Object.assign({}, vdata.searchData, {'pageSize': -1})).then(res => {
        fileDownload(res.data, '会员信息.xlsx')
    }).catch ((error) =>{console.log(error)} )
  }

  // 数据统计
  const getCount = () => {
    $memberInfoCount(vdata.searchData).then( res => {
      console.log(res)
      countList.value = [ 
        {title: '会员总数', symbol: 'add', content: res.memberNum, isMoney: false},
        {type: 'line'},
        {title: '会员总余额', symbol: 'add', textColor: '#1A66FF', isMoney: true, content: ((res.balance) / 100).toFixed(2)},
        {type: 'line'},
        {title: '充值支付金额', textColor: '#1A66FF', isMoney: true, content: (res.payAmount / 100).toFixed(2)},
        {type: 'line'},
        {title: '消费金额',symbol: 'sub', isAmount: true, content: (Math.abs(res.changeAmount) / 100).toFixed(2)},
      ]
    })
  }

  function onReset(){
    //重置搜索内容
    dateRangePicker.value.returnSelectModel()
    vdata.searchData = { queryDateRange: '' }
  }
 
</script>

<style lang="less" scoped>
</style>
